<?php

/**
 * product actions.
 *
 * @package    Manager
 * @subpackage product
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class productActions extends sfActions
{
	//get form data
	var $client_name ;
	var $clientcharge_name ;
	var $clientcharge_email ="" ;
	var $blogger_name ;
	var $product_name ;
	var $url ;
	var $date;
	var $starttime;
	var $endtime;
	var $startdate;
	var $enddate ;
	var $pledgetime ;
	var $sale;
	var $client_note;
	var $client_payment_time;
	var $client_request_date;
	var $agent_request_date;
	var $agent_name ;
	var $agentcharge_name ;
	var $agentcharge_email ="";
	var $cost;
	var $deadline ;
	var $agent_note ;
	var $agent_payment_time;

	public function executeIndex(sfWebRequest $request)
	{
		$this->products = Doctrine_Core::getTable('Product')
		->createQuery('a')
		->execute();
		$this->users = Doctrine_Core::getTable('User')
		->createQuery('a')
		->execute();
	}

	public function executeRequest(sfWebRequest $request){
		if($request->hasParameter("month")){
			$this->rMonth= $request->getParameter("month");
			$this->products = Doctrine_Core::getTable("Product")->getProductInMonth($this->rMonth);
		}else{
			$today = getdate();
			$this->rMonth = $today['year']."-".$this->convertTimeFormat($today['mon']);
			$this->products = Doctrine_Core::getTable("Product")->getProductInMonth($this->rMonth);
		}
		
		$results = Doctrine_Core::getTable('Product')->getRequestMonth();
		$this->dates = array();

		foreach ($results as $r){
			$month = $this->getYearMonth($r->getClient_request_date());
			if(!array_key_exists($month, $this->dates)){
				$this->dates[$month] = $month;
			}
		}
	}

	function getYearMonth($date){
		$day = strtotime($date);
		$year = date("Y",$day);
		$month = date("m",$day);
		return $year."-".$month;
	}
	public function executeShow(sfWebRequest $request)
	{
		$this->product = Doctrine_Core::getTable('Product')->find(array($request->getParameter('id')));
		$this->forward404Unless($this->product);
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->start = $request->getParameter("start","null");
		$this->allDay = $request->getParameter("allDay","null");
		$this->end = $request->getParameter("end","null");
		$this->dead = $request->getParameter("deadline","null");
		$this->email = $this->getUser()->getAttribute('email');
		$this->form = new ProductForm();

	}

	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));

		$this->form = new ProductForm();

		$this->processForm($request, $this->form);

		$this->setTemplate('new');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$this->forward404Unless($product = Doctrine_Core::getTable('Product')->find(array($request->getParameter('id'))), sprintf('Object product does not exist (%s).', $request->getParameter('id')));
		$this->form = new ProductForm($product);
	}

	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$this->forward404Unless($product = Doctrine_Core::getTable('Product')->find(array($request->getParameter('id'))), sprintf('Object product does not exist (%s).', $request->getParameter('id')));
		$this->form = new ProductForm($product);

		$this->processForm($request, $this->form);

		$this->setTemplate('edit');
	}

	public function executeDelete(sfWebRequest $request)
	{
		$request->checkCSRFProtection();

		$this->forward404Unless($product = Doctrine_Core::getTable('Product')->find(array($request->getParameter('id'))), sprintf('Object product does not exist (%s).', $request->getParameter('id')));
		$product->delete();

		$this->redirect('product/index');
	}

	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
		if ($form->isValid())
		{

			//get form data
			$product = $request->getParameter("product");
			$this->client =$product["client"];
			$this->clientcharge_name = $product["clientcharge_name"];
			//$this->clientcharge_email = $product["clientcharge_email"];
			$this->blogger_id = $product["blogger_id"];
			$this->product_name = $product["product"];
			$this->url = $product["url"];
			$this->date = $product["date"];

			$starttime_hour = $product["starttime"]["hour"];
			$starttime_hour = $this->convertTimeFormat($starttime_hour);
			$starttime_minute = $product["starttime"]["minute"];
			$starttime_minute = $this->convertTimeFormat($starttime_minute);

			$this->starttime = $starttime_hour.":".$starttime_minute;
			$this->startdate = $this->date." ".$this->starttime;

			$endtime_hour = $product["endtime"]["hour"];
			$endtime_hour = $this->convertTimeFormat($endtime_hour);
			$endtime_minute = $product["endtime"]["minute"];
			$endtime_minute = $this->convertTimeFormat($endtime_minute);
			$this->endtime = $endtime_hour.":".$endtime_minute;
			$this->enddate = $this->date." ".$this->endtime;
			$this->pledgetime = $product["pledgetime"];
			$this->sale = $product["sale"];
			$this->client_note = $product["client_note"];


			$this->client_payment_time= $product["client_payment_time"];

			$this->client_request_date = $product["client_request_date"];
			$this->agent_request_date = $product["agent_request_date"];

			$this->agent = $product["agent"];
			$this->agentcharge_name = $product["agentcharge_name"];
			//$this->agentcharge_email = $product["agentcharge_email"];
			$this->cost = $product["cost"];

			$deadline_date = $product["deadline_date"];
			$deadline_time_hour = $product["deadline_time"]["hour"];
			$deadline_time_minute = $product["deadline_time"]["minute"];
			$this->deadline = $deadline_date." ".$deadline_time_hour.":".$deadline_time_minute;
			$this->agent_note = $product["agent_note"];


			$this->agent_payment_time= $product["agent_payment_time"];
			$user_gmail = $product["user_gmail_acount"];
			$user_gmail_pass = $product["user_gmail_password"];

			if($this->checkValid($this->client,$this->blogger_id,$this->startdate,$this->enddate)){
				//add client charge
				$clt = Doctrine_Core::getTable("Client")->find(array($this->client));
				$clientcharge;
				if($clt){
					$this->client_name = $clt->getName();
					$clientcharge = Doctrine_Core::getTable("ClientCharge")->findByNameAndClientId($this->clientcharge_name,$this->client);
					if(count($clientcharge) == 0){
						$clientcharge = new ClientCharge();

						$clientcharge->setClient($clt);
						$clientcharge->setName($this->clientcharge_name);
						$clientcharge->setEmail($this->clientcharge_email);
						$clientcharge->save();
					}
				}
				//add agent charge
				$agt = Doctrine_Core::getTable("Agent")->find(array($this->agent));
				$agentcharge;
				if($agt){
					$this->agent_name = $agt->getName();
					$agentcharge = Doctrine_Core::getTable("AgentCharge")->findByNameAndAgentId($this->agentcharge_name,$this->agent);
					if(count($agentcharge) == 0){
						$agentcharge = new AgentCharge();
						$agentcharge->setAgent($agt);
						$agentcharge->setName($this->agentcharge_name);
						$agentcharge->setEmail($this->agentcharge_email);
						$agentcharge->save();
					}
				}
				//find user
				$user = Doctrine_Core::getTable("User")->findByLoginId($this->getUser()->getAttribute("id"));
				$blogger = Doctrine_Core::getTable("Blogger")->find(array($this->blogger_id));
				$this->blogger_name = $blogger->getName();

				$clientcharge = Doctrine_Core::getTable("ClientCharge")->findByNameAndClientId($this->clientcharge_name,$this->client);
				$agentcharge = Doctrine_Core::getTable("AgentCharge")->findByNameAndAgentId($this->agentcharge_name,$this->agent);
				//create new product
				$newProduct = new Product();

				$newProduct->setClientCharge($clientcharge[0]);
				$newProduct->setAgentCharge($agentcharge[0]);
				$newProduct->setBlogger($blogger);
				$newProduct->setUser($user[0]);
				$newProduct->setProduct($this->product_name);
				$newProduct->setUrl($this->url);
				$newProduct->setStartdate($this->startdate);
				$newProduct->setEnddate($this->enddate);
				$newProduct->setPledgetime($this->pledgetime);
				$newProduct->setSale($this->sale);
				$newProduct->setClient_note($this->client_note);
				$newProduct->setClient_payment_time($this->client_payment_time);
				$newProduct->setClient_request_date($this->client_request_date);
				$newProduct->setAgent_request_date($this->agent_request_date);
				$newProduct->setCost($this->cost);
				$newProduct->setDeadline($this->deadline);
				$newProduct->setAgent_note($this->agent_note);
				$newProduct->setAgent_payment_time($this->agent_payment_time);

				$newProduct->save();

				//send to client
				$check = $this->sendMail($user_gmail,$user_gmail_pass,"all@eure.jp",$this->makeClientMessage());

				//send to agent
				$check = $this->sendMail($user_gmail,$user_gmail_pass,"all@eure.jp",$this->makeAgentMessage());

				if($check)
				$this->redirect('product/index');
				else
				$this->redirect('product/error');
					
			}
			else{
				$this->redirect('product/error');
			}
		}

	}
	function emailSplit($string){
		$emails = spliti(",", $string);
		return $emails;
	}
	/**
	 * 1 -> 01
	 * @param unknown_type $string
	 */
	function convertTimeFormat($string){
		$result = $string;
		$value = (int)$string;
		if($value < 10)
		$result = "0".$string;
		return $result;
	}
	/**
	 *
	 * convert 2001-10-30 format to 2001年10月30日
	 * @param unknown_type $string
	 */
	function convertDateFormat($string){
		$date_split = spliti("-", $string);
		return $date_split[0]."年".$date_split[1]."月".$date_split[2]."日";
	}
	function makeClientMessage(){
		$message ="<p style=''>";
		$message .= $this->clientcharge_name."様<br/><br/>";
		$message .="お世話になっております。 <br/>";
		$message .="エウレカの".$this->getUser()->getAttribute("name")."です。<br/><br/>";
		$message .="この度は、ありがとう御座いました。<br/>";
		$message .="ブログ広告のご発注メールをお送りいたしますので、<br/>ご確認いただき、問題なければ、受領メールをお返しください。 <br/><br/>";
		$message .="-----------------------------------------------------------------------------------------<br/><br/>";
		$message .= "御社名　　　　: ".$this->client_name."様<br/>";
		$message .= "商品　　　　　:　".$this->product_name." <br/>";
		$message .= "URL　　　　　:　".$this->url."<br/>";
		$message .= "ブロガー　　　 :　".$this->blogger_name."さん<br/>";
		$message .= "掲載開始時間　:　".$this->convertDateFormat($this->date)." ".$this->dayOfWeek($this->date)." ".$this->starttime."~".$this->endtime."　頃 <br/>";
		$message .= "価格　　　　　:　".number_format($this->sale)."円 (税別)<br/>";
		$message .= "御請求日　　　:  ".$this->convertDateFormat($this->client_request_date)." ".$this->dayOfWeek($this->client_request_date)."<br/>";
		$message .= "お支払い日　　:　".$this->convertDateFormat($this->client_payment_time)." ".$this->dayOfWeek($this->client_payment_time)."<br/>";
		$message .= "備考　　　　　:　".$this->client_note."<br/><br/>";
		$message .="-----------------------------------------------------------------------------------------<br/><br/>";
		$message .="よろしくお願い致します。";
		$message .="</p>";
		return $message;
	}
	// make message to send to agent
	function makeAgentMessage(){
		$message ="";
		$message .= $this->agentcharge_name."様<br/><br/>";
		$message .="お世話になっております。 <br/>";
		$message .="エウレカの".$this->getUser()->getAttribute("name")."です。<br/><br/>";
		$message .="この度は、ありがとう御座いました。<br/>";
		$message .="ブログ広告のご発注メールをお送りいたしますので、<br/>ご確認いただき、問題なければ、受領メールをお返しください。 <br/><br/>";
		$message .="-----------------------------------------------------------------------------------------<br/><br/>";
		$message .= "御社名　　　　: ".$this->agent_name."様 <br/>";
		$message .= "商品　　　　　:　".$this->product_name."<br/>";
		$message .= "URL　　　　　:　".$this->url."<br/>";
		$message .= "ブロガー　　　 :　".$this->blogger_name."さん<br/>";
		$message .= "掲載開始時間　:　".$this->convertDateFormat($this->date)." ".$this->dayOfWeek($this->date)." ".$this->starttime."~".$this->endtime."　頃<br/>";
		$message .= "価格　　　　　:　".number_format($this->cost)."円(税別)<br/>";
		$message .= "御請求日　　　:  ".$this->convertDateFormat($this->agent_request_date)." ".$this->dayOfWeek($this->agent_request_date)."<br/>";
		$message .= "お支払い日　　:　".$this->convertDateFormat($this->agent_payment_time)." ".$this->dayOfWeek($this->agent_payment_time)."<br/>";
		$message .= "備考　　　　　:　".$this->agent_note."<br/><br/>";
		$message .="-----------------------------------------------------------------------------------------<br/><br/>";
		$message .="よろしくお願い致します。";

		return $message;
	}
	/*
	 *
	 */
	function dayOfWeek($date){
		$dayofweek = array("Monday"=>"(月)","Tuesday"=>"(火)","Wednesday"=>"(水)","Thursday"=>"(木)","Friday"=>"(金)","Saturday"=>"(土)","Sunday"=>"(日)");
		$day = date("l",strtotime($date));
		return $dayofweek[$day];
	}
	/*
	 * $option: client or blogger
	 */
	function sendMail($user,$pass,$to,$content){
		require_once sfConfig::get('sf_lib_dir').'/vendor/Swift-4.0.6/lib/swift_init.php';
		$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com');

		$transport->setUsername($user);
		$transport->setPassword($pass);
		$transport->setPort(465);
		$transport->setEncryption('ssl');

		/*send message*/
		$mailer = Swift_Mailer::newInstance($transport);

		if($mailer){
			$message = Swift_Message::newInstance();

			$message->setFrom(array($user=>$this->getUser()->getAttribute('name')));
			$message->setTo($to);
			$message->setCc(array("media@eure.jp"));

			$message->setSubject('【株式会社エウレカ】ブログ広告ご発注メール');
			$message->setBody($content,'text/html');

			if($mailer->send($message)){
				return true;
			}
			else{
				return false;
			}
		}else{
			return false;
		}
	}
	public function executeError(sfWebRequest $request){

	}
	public function checkValid($client, $blogger, $startdate, $enddate){
		$products = Doctrine_Core::getTable("Product")->getProductsWithBloggerAndClient($client,$blogger);
		if($products == null)
		return true;
		foreach ($products as $product){
			$s = date("Y-m-d",strtotime($product->getStartdate()));
			$s_in = date("Y-m-d",strtotime($startdate));
			if($s == $s_in)
			return false;
		}
		return true;
	}
	public function executeClientChargeList(sfWebRequest $request){
		$client_id = $request->getParameter("client");
		$clcharges = Doctrine_Core::getTable("ClientCharge")->findByClientId($client_id);
		$result = "";
		$len = count($clcharges);
		for($index = 0; $index < $len; $index++){
			$result .= $clcharges[$index]->getName();
			if($index != $len - 1)
			$result .=",";
		}
		return $this->renderText($result);
	}
	public function executeAgentChargeList(sfWebRequest $request){
		$agent_id = $request->getParameter("agent");
		$charges = Doctrine_Core::getTable("AgentCharge")->findByAgentId($agent_id);
		$result = "";
		$len = count($charges);
		for($index = 0; $index < $len; $index++){
			$result .= $charges[$index]->getName();
			if($index != $len - 1)
			$result .=",";
		}
		return $this->renderText($result);
	}
}
